/**
 * [format 字符串格式化函数]
 * @param  {[String]} args [替换的数据]
 * @return {[String]}      [格式化后的字符串]
 */
String.prototype.format = function (args) {
	var result = this;
	if (arguments.length > 0) {
		if (arguments.length === 1 && typeof (args) == "object") {
			for (var key in args) {
				if (args[key] !== undefined) {
					var reg = new RegExp("({" + key + "})", "g");
					result = result.replace(reg, args[key]);
				}
			}
		} else {
			for (var i = 0; i < arguments.length; i++) {
				if (arguments[i] !== undefined) {
					var reg = new RegExp("({[" + i + "]})", "g");
					result = result.replace(reg, arguments[i]);
				}
			}
		}
	}
	return result;
};

var icons = {
	'file-code-o': 'xml|html?|haml|php|aspx?|js|(le|sa|s?c)cs|bat|cmd|vbs|java|smali|py',
	'file-archive-o': 'zip|rar|gz|7z',
	'android': 'apk|jar|dex',
	'apple': 'ipa|dmg',
	'windows': 'iso|esd|exe|msi',
	'file-text-o': 'plain|log|msg|odt|page|te?xt|ext|md|ini|conf|svg',
	'file-audio-o': 'aac|mid|wma|ogg|m4a|mp3|ape|flac|wav|d[sd]f',
	'file-image-o': 'bmp|jpe?g|png|ico|[tg]if|pc[cx]|tga|exif|fpx|psd|cdr|dxf|ufo|eps|ai|raw|wmf|webp',
	'file-movie-o': '3gp|avi|mkv|mp4|flv|rmvb|mov|wmv',
	'file-word-o': 'docx?',
	'file-excel-o': 'xl(s[xm]?|t)',
	'file-pdf-o': 'pdf',
	'database': 'db|sql'
};

function args (name) {
	if (typeof (name) === 'undefined' || name === '') return '';

	var re    = /^#([a-z0-9]{5,10}|-1)?(\?(.+))?$/.exec(location.hash),
	    param = {id: -1};

	if (re) {
		param.id = re[1] || '-1';

		if (re[3]) {
			var query = re[3].split('&');
			for (var i = 0; i < query.length; i++) {
				var a = query[i].split('=');
				param[a[0]] = a[1];
			}
		}
	}

	return param.hasOwnProperty(name) ? param[name] : '';
}

function parseUrl (id, pwd) {
	var uri = id;
	if (typeof (id) === 'undefined' || id === '') uri = args('id');

	if (typeof (pwd) !== 'undefined' && pwd !== '') uri += '?pwd=' + pwd;
	return uri;
}

function fullUrl (obj) {
	var uri = obj.id;
	if (obj.hasOwnProperty('name')) uri += '/' + obj.name;
	else if (obj.hasOwnProperty('ext') && obj.ext !== '') uri += '.' + obj.ext;
	if (obj.hasOwnProperty('name') && curr_page > 1) uri += '?page=' + curr_page;
	return location.href.replace(/[#?].*$/g, '') + uri;
}

layui.config({
	base: "js/lay-module/",
	version: true
}).extend({
	lianyi: 'lianyi'
}).use(['jquery', 'layer', 'table', 'form', 'lianyi'], function () {
	var $      = layui.jquery,
	    layer  = layui.layer,
	    table  = layui.table,
	    form   = layui.form,
	    lianyi = layui.lianyi;

	window.cut_file = {};

	var parseLayer = function (msg) {
		return layer.open({
			title: '涟漪云 (更新于：<b style="color:red">2021-05-20</b>)',
			type: 1,
			closeBtn: false,
			shadeClose: true,
			content: $('#lanzou'),
			btn: [window.isAdmin ? '设置' : '确定', '取消'],
			id: 'parseLayer',
			success: function (elem, index) {
				if (msg) lianyi.fail(msg);
				form.val('lanzou', {id: args('id'), pwd: window.isAdmin ? (window.pwd || '') : args('pwd')});
				var that = this;
				$('[name]', elem).keydown(function (e) {
					if (e.keyCode === 13)
						that.yes(index, elem);
				});
			},
			yes: function (index, elem) {
				var field = form.val('lanzou');

				var re = /^([0-9a-zA-Z]{5,10}|-1)?$/.exec(field.id);
				if (!re)
					lianyi.fail('目录id不正确');

				if (window.isAdmin) {
					if (window.pwd === field.pwd) return lianyi.fail('无变化');
					lianyi.request({
						url: 'api.php?c=pwd',
						data: field,
						msg: '设置密码...',
						success: function (res) {
							window.pwd = field.pwd;
							layer.close(index);
						}
					});
				} else {
					layer.close(index);
					location.hash = parseUrl(field.id || -1, field.pwd);
				}
			}
		});
	}

	var refresh = function () {
		if (!args('id'))
			return lianyi.fail('请输入正确的目录id');

		layer.closeAll()

		var where = {id: args('id'), pwd: args('pwd'), page: 1};

		if (table.cache.hasOwnProperty('list'))
			return table.reload('list', {
				where: where
			});

		return table.render({
			elem: '#list',
			url: 'api.php?c=list',
			method: 'POST',
			where: where,
			toolbar:
				'<div>' +
				'   <div class="table-toolbar">'+
				'       <button type="button" class="layui-btn layui-btn-sm" lay-event="refresh">刷新</button>' +
				'       <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" lay-event="change">更改</button>' +
				'       <div class="layui-btn-group toolbar-admin layui-hide">' +
				'           <button type="button" class="layui-btn layui-btn-sm layui-hide" lay-event="folder" tips="新建文件夹"><i class="fa fa-folder fa-fw"></i></button>' +
				'           <button type="button" class="layui-btn layui-btn-sm layui-hide" lay-event="cut" tips="剪贴"><i class="fa fa-cut fa-fw"></i></button>' +
				'           <button type="button" class="layui-btn layui-btn-sm layui-hide" lay-event="paste" tips="粘贴"><i class="layui-icon layui-icon-release"></i></button>' +
				'           <button type="button" class="layui-btn layui-btn-sm layui-hide" lay-event="delete" tips="删除"><i class="fa fa-trash fa-fw"></i></button>' +
				'       </div>' +
				'   </div>'+
				'</div>'
			,
			defaultToolbar: ['filter'],
			height: 'full-106',
			cols: [[
				{type: 'checkbox', title: '全选', id: 'checkAll', width: 40, fixed: 'left'},
				{type: 'numbers', title: '序号', width: 50, fixed: 'left'},
				{
					field: 'name', title: '名称', minWidth: 160, templet: function (d) {
						if (d.isFolder)
							return '<a href="#{0}"><i class="fa fa-folder fa-fw" style="margin-right: 5px;"></i>{1}</a>'.format(d.id, d.name);

						var icon = 'file-o',
						    ext  = d.ext;

						if (ext)
							$.each(icons, function (k, v) {
								var re = new RegExp('^' + v + '$', 'i');
								if (re.test(ext)) {
									icon = k;
									return false;
								}
							});

						return '<a href="{0}"><i class="fa fa-{1} fa-fw" style="margin-right: 5px;"></i>{2}</a>'.format(d.id, icon, d.name);
					}, sort: true
				},
				{field: 'size', title: '大小', width: 85, sort: true},
				{field: 'downs', title: '下载', width: 85, sort: true},
				{field: 'time', title: '时间', width: 102, sort: true, hide: true},
				{
					title: '操作', width: 112, fixed: 'right', event: 'action', templet: function (d) {
						if (d.isFolder && !isAdmin) return '';

						var html = '<select lay-filter="action">';
						html += '<option value="">操作</option>';
						if (!d.isFolder)
							html += '<option value="links">直链</option>';

						if (isAdmin) {
							html += '<optgroup label="管理员">';
							if (!d.isFolder) html += '<option value="cut">剪切</option>';
							html += '<option value="rename">重命名</option>';
							html += '<option value="delete">删除</option>';
							html += '</optgroup>';
						}
						html += '</select>';

						return html;
					}
				}
			]],
			page: false,
			parseData: function (res) {
				window.curr_page = this.where.page;
				window.isAdmin = res.admin === true;
				window.pwd = res.pwd || '';
			},
			done: function (res) {
				cut_files(true);
				$('.toolbar-admin, .toolbar-admin [lay-event="folder"]')[window.isAdmin ? 'removeClass' : 'addClass']('layui-hide');
				if (res.path)
					$('#nav').html(function () {
						var navs = ['<a href="#{0}">{1}</a>'.format(parseUrl(-1), '根目录')]
						$.each(res.path, function (id, name) {
							navs.push('<a href="#{0}">{1}</a>'.format(parseUrl(id), name));
						});
						return navs.join('<span lay-separator="">/</span>')
					});
				var bool = curr_page > 1;
				$('#page_prev')[bool ? 'removeClass' : 'addClass']('layui-btn-disabled').prop('disabled', !bool);

				bool = res.data && res.data.length > 0;
				$('#page_next')[bool ? 'removeClass' : 'addClass']('layui-btn-disabled').prop('disabled', !bool);

				if (res.code < 0) {
					setTimeout(function () {
						parseLayer(res.msg);
					}, 200);
				}
			}
		});
	}

	refresh();

	table.on('toolbar(list)', function (obj) {
		var event = obj.event,
		    d     = obj.data;
		switch (event) {
			case 'refresh':
				refresh();
				break;
			case 'change':
				parseLayer();
				break;
			case 'folder':
				layer.prompt({
						title: '新建文件夹',
						formType: 0,
						shadeClose: true,
						success: function (elem) {
						}
					},
					function (val, index) {
						val = $.trim(val);
						if (val === '')
							return lianyi.fail('文件夹名称不能为空！');

						lianyi.request({
							url: 'api.php?c=folder',
							data: {id: args('id'), name: val},
							msg: '新建文件夹...',
							success: function (res) {
								layer.close(index);
							}
						});
					}
				);
				break;
			case 'cut':
				var checkStatus = table.checkStatus('list'),
				    checkeds    = checkStatus.data;

				cut_files(checkeds);
				$('.layui-table-fixed-l input[type="checkbox"][name="layTableCheckbox"]:checked').next('.layui-form-checked').click();
				break;
			case 'paste':
				layer.confirm(Object.values(cut_file).join('<hr>'), {
					title: '确认移动以下文件到此目录',
					shadeClose: true,
					btn: ['移动', '清空', '取消'],
					btn1: function (index) {
						lianyi.request({
							url: 'api.php?c=move',
							data: {id: args('id'), file_id: Object.keys(cut_file)},
							msg: '移动文件...',
							success: function (res) {
								layer.close(index);
							},
							complete: function (res) {
								cut_files();
							}
						});
						return false;
					},
					btn2: function (index) {
						cut_files();
					}
				});
				break;
			case 'delete':
				checkStatus = table.checkStatus('list');
				checkeds = checkStatus.data;

				var folder = {}, file = {};
				$.each(checkeds, function (i, v) {
					if (v.isFolder) folder[v.id] = v.name;
					else file[v.id] = v.name;
				});

				layer.confirm(Object.values(folder).concat(Object.values(file)).join('<hr>'), {
					title: '确认删除以下文件（夹）',
					shadeClose: true,
					btn: ['删除', '取消'],
					btn1: function (index) {
						lianyi.request({
							url: 'api.php?c=delete',
							data: {id: args('id'), file_id: Object.keys(file), folder_id: Object.keys(folder)},
							msg: '删除文件（夹）...',
							success: function (res) {
								layer.close(index);
							}
						});
						return false;
					}
				});
				break;
		}
	});

	table.on('checkbox(list)', function (obj) {
		var checkStatus = table.checkStatus('list'),
		    checkeds    = checkStatus.data;

		var file = {};
		$.each(checkeds, function (i, v) {
			if (!v.isFolder) file[v.id] = v.name;
		});

		$('.toolbar-admin, .toolbar-admin [lay-event="folder"]')[window.isAdmin ? 'removeClass' : 'addClass']('layui-hide');
		if (window.isAdmin) {
			$('.toolbar-admin [lay-event="cut"]')[Object.keys(file).length > 0 ? 'removeClass' : 'addClass']('layui-hide');
			$('.toolbar-admin [lay-event="delete"]')[checkeds.length > 0 ? 'removeClass' : 'addClass']('layui-hide');
		}
	});

	table.on('tool(list)', function (obj) {
		var d     = obj.data,
		    event = obj.event;

		switch (event) {
			case 'action':
				window.row_obj = obj;
				break;
		}
	});

	form.on('select(action)', function (obj) {
		var elem  = obj.elem,
		    value = obj.value,
		    d     = row_obj.data;

		switch (value) {
			case 'links':
				var links = [
					fullUrl({id: d.id, ext: d.ext}),
					fullUrl({id: args('id'), name: d.name})
				];
				layer.open({
					title: '文件直链',
					type: 1,
					shadeClose: true,
					content:
						'<div class="layui-form layui-form-pane" lay-filter="links" style="padding: 20px">' +
						'	<div class="layui-form-item">' +
						'		<label class="layui-form-label">直链1(推荐)</label>' +
						'       <div class="layui-input-inline">' +
						'		    <input type="text" id="link1" value="{0}" class="layui-input" readonly>'.format(links[0]) +
						'	    </div>' +
						'	</div>' +
						'	<div class="layui-form-item">' +
						'		<label class="layui-form-label">直链2</label>' +
						'       <div class="layui-input-inline">' +
						'		    <input type="text" id="link2" value="{0}" class="layui-input" readonly>'.format(links[1]) +
						'	    </div>' +
						'	</div>' +
						'</div>'
					,
					btn: ['关闭']
				});
				break;
			case 'cut':
				var file = {};
				file[d.id] = d.name;
				cut_files(file);
				break;
			case 'rename':
				layer.prompt({
						title: '重命名(非文件夹需要会员)',
						formType: 0,
						shadeClose: true,
						value: d.name,
						success: function (elem) {
						}
					},
					function (val, index) {
						val = $.trim(val);
						if (val === '')
							return lianyi.fail('文件(夹)名称不能为空！');

						lianyi.request({
							url: 'api.php?c=rename',
							data: {id: d.id, name: val},
							msg: '重命名...',
							success: function (res) {
								row_obj.update({name: val});
								layer.close(index);
							}
						});
					}
				);
				break;
			case 'delete':
				var data = {id: args('id')};
				data[d.isFolder ? 'folder_id' : 'file_id'] = d.id;
				layer.confirm('确认删除文件{0}：<b style="color: red;">{1}</b> ？'.format(d.isFolder ? '夹' : '', d.name), {
					title: '删除文件' + (d.isFolder ? '夹' : ''),
					shadeClose: true,
					btn: ['删除', '取消'],
					btn1: function (index) {
						lianyi.request({
							url: 'api.php?c=delete',
							data: data,
							msg: '正在删除...',
							success: function (res) {
								layer.close(index);
							}
						});
						return false;
					}
				});
				break;
		}
	});

	function cut_files (id) {
		if (typeof (window.cut_file) === 'undefined')
			window.cut_file = {};

		if (!window.isAdmin) return;

		if (typeof (id) === 'undefined')
			window.cut_file = {};
		else if (id instanceof Array)
			$.each(id, function (i, v) {
				if (!v.isFolder) window.cut_file[v.id] = v.name;
			});
		else if (id instanceof Object)
			window.cut_file = $.extend(window.cut_file, id);

		var len = Object.keys(window.cut_file).length;
		if (len > 0)
			$('.toolbar-admin [lay-event="paste"]').removeClass('layui-hide').html('<i class="layui-icon layui-icon-release"></i><span class="layui-badge">{0}</span>'.format(len));
		else
			$('.toolbar-admin [lay-event="paste"]').addClass('layui-hide').html('<i class="layui-icon layui-icon-release"></i>');
	}

	$('#page_prev').on('click', function (e) {
		table.reload('list', {
			where: {
				page: curr_page - 1
			}
		}, true);
	});

	$('#page_next').on('click', function (e) {
		table.reload('list', {
			where: {
				page: curr_page + 1
			}
		}, true);
	});

	$('.nav-admin').on('click', function (e) {
		if (window.isAdmin)
			return layer.confirm('您已登录，现在退出管理员登录 ？', {
				title: '退出登录',
				shadeClose: true,
				btn: ['退出', '取消'],
				btn1: function (index) {
					lianyi.request({
						url: 'api.php?c=logout',
						msg: '退出登录...',
						success: function (res) {
							layer.close(index);
						}
					});
					return false;
				}
			});

		layer.open({
			title: '管理员登录',
			type: 1,
			shadeClose: true,
			content:
				'<div class="layui-form" id="login" lay-filter="login" style="padding: 20px">' +
				'	<div class="layui-form-item">' +
				'		<label class="layui-icon layui-icon-password"></label>' +
				'		<input type="text" name="pass" lay-verify="required" placeholder="管理员密码" lay-reqtext="请输入密码" autocomplete="off" maxlength="32" class="layui-input">' +
				'	</div>' +
				'	<div class="layui-form-item code-item">' +
				'		<label class="layui-icon layui-icon-vercode"></label>' +
				'		<input type="text" name="code" lay-verify="required" placeholder="图形验证码" lay-reqtext="请输入图形验证码" autocomplete="off" maxlength="4" class="layui-input code-input">' +
				'		<div class="code-img">' +
				'			<img src="api.php?c=verify" alt="图形验证码">' +
				'		</div>' +
				'	</div>' +
				'</div>'
			,
			btn: ['登录', '取消'],
			id: 'parseLayer',
			success: function (elem, index) {
				$('.code-img > img', elem).on('click', function () {
					$(this).attr('src', 'api.php?c=verify&t=' + Math.random());
				});
				$('input[name]', elem).on('input propertychange', function () {
					var val = $(this).val();
					switch ($(this).attr('name')) {
						case 'pass':
							if (/\s+/.test(val)) $(this).val(val.replace(/\s+/g, ''));
							break;
						case 'code':
							if (/[^0-9a-zA-Z]/.test(val)) $(this).val(val.replace(/[^0-9a-zA-Z]/g, ''));
							break;
					}
					$(this).prev().css('color', $(this).val() === '' ? '#d2d2d2' : '#1e9fff');
				});
				var that = this;
				$('input[name]', elem).keydown(function (e) {
					if (e.keyCode === 13)
						that.yes(index, elem);
				});
			},
			yes: function (index, elem) {
				var field = form.val('login');
				if (field.pass === '') return lianyi.fail('管理员密码不能为空');
				if (field.code === '') return lianyi.fail('图形验证码不能为空');
				lianyi.request({
					url: 'api.php?c=login',
					data: field,
					success: function (res) {
						layer.close(index);
					},
					complete: function (res) {
						if (res.code >= 0)
							$('.code-img > img', elem).click();
					}
				});
			}
		});
	});

	$('#lanzou input[name="id"]').on('input propertychange', function () {
		var val = $(this).val();
		if (/[^a-z0-9\-]/.test(val)) $(this).val(val.replace(/[^a-z0-9\-]/g, ''));
	});

	$('#lanzou input[name="pwd"]').on('input propertychange', function () {
		var val = $(this).val();
		if (/^\s+|\s+$/.test(val)) $(this).val(val.replace(/^\s+|\s+$/g, ''));
	});

	$(window).on('hashchange', function (e) {
		refresh();
	});
});